import axios, {
  AxiosInstance,
  AxiosError,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";
import {
  showFullScreenLoading,
  tryHideFullScreenLoading,
} from "@/components/Loading/fullScreen";
import { LOGIN_URL, HTTP_BASE_URL } from "@/config";
import { ResultEnum } from "@/enums/httpEnum";
import { message } from "@/hooks/useMessage";
import { setToken } from "@/redux/modules/user";
import { store } from "@/redux";
import { StorageKey } from "@/enums/dictionaries";

//如果需要Loading
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean;
}

const config = {
  baseURL: HTTP_BASE_URL,
  timeout: ResultEnum.TIMEOUT as number,
  // Credentials are allowed to be carried across domains
  withCredentials: false,
  headers: {},
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config);

    /**
     * @description request interceptor
     */
    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        config.loading && showFullScreenLoading();
        const token = localStorage.getItem(StorageKey.token);
        if (
          token &&
          config.headers &&
          typeof config.headers.set === "function"
        ) {
          config.headers.set("Authorization", `Bearer ${token}`);
        }

        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      },
    );

    /**
     * @description response interceptor
     *  The server returns the information -> [intercept unified processing] -> the client JS gets the information
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response;

        tryHideFullScreenLoading();
        // login failure
        if (data.code == ResultEnum.OVERDUE) {
          store.dispatch(setToken(""));
          // message.error(data.msg);
          // window.navigate(LOGIN_URL);
          return Promise.reject(data);
        }
        // 全局错误处理
        if (data.code && data.code !== ResultEnum.SUCCESS) {
          message.error(data.msg);
          return Promise.reject(data);
        }
        return data;
      },
      async (error: AxiosError) => {
        const { response } = error;
        tryHideFullScreenLoading();
        // if (error.message.indexOf("timeout") !== -1) message.error("请求超时！请您稍后重试");
        // if (error.message.indexOf("Network Error") !== -1) message.error("网络错误！请您稍后重试");
        // @ts-ignore 未登录
        if (error?.response?.data?.errCode === 401) {
          localStorage.removeItem(StorageKey.token);
          location.replace("/login");
        }
        return Promise.reject(error);
      },
    );
  }

  /**
   * @description Common request method encapsulation
   */
  get<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object | string, _object = {}): Promise<any> {
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<any> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
}

export default new RequestHttp(config);
